package com.feather.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipUtil {
	public static boolean is(byte[] bytes) {
		return (bytes != null && bytes.length >= 2) ? ((bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8)) == GZIPInputStream.GZIP_MAGIC : false;
	}

	public static boolean is(String str) {
		try {
			return str != null ? is(str.getBytes("UTF-8")) : false;
		} catch (UnsupportedEncodingException ex) {
			return false;
		}
	}

	public static byte[] compress(byte[] bytes) throws IOException {
		byte[] enBytes = null;
		if (bytes != null && bytes.length > 0) {
			GZIPOutputStream gzipos = null;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			try {
				gzipos = new GZIPOutputStream(baos);
				gzipos.write(bytes);
				enBytes = baos.toByteArray();
			} catch (IOException ex) {
				throw ex;
			} finally {
				if (gzipos != null) {
					try {
						gzipos.close();
					} catch (IOException ex) {
					}
				}
				try {
					baos.close();
				} catch (IOException ex) {
				}
			}
		}
		return enBytes;
	}

	public static byte[] uncompress(byte[] bytes) throws IOException {
		byte[] deBytes = null;
		if (bytes != null && bytes.length > 0) {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
			GZIPInputStream gzipis = null;
			try {
				gzipis = new GZIPInputStream(bais);
				byte[] buffer = new byte[512];
				int n;
				while ((n = gzipis.read(buffer)) >= 0) {
					baos.write(buffer, 0, n);
				}
				deBytes = baos.toByteArray();
			} catch (IOException ex) {
				throw ex;
			} finally {
				if (gzipis != null) {
					try {
						gzipis.close();
					} catch (IOException ex) {
					}
				}
				try {
					bais.close();
				} catch (IOException ex) {
				}
				try {
					baos.close();
				} catch (IOException ex) {
				}
			}
		}
		return deBytes;
	}
}
